#!/usr/bin/env python
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run Chameleon Daemon."""

import argparse
import logging
import shlex

from chameleond.chameleon_server import ChameleonServer


def main():
  """The Main program, to run Chameleon Daemon."""
  parser = argparse.ArgumentParser(
      description='Launch a Chameleon daemon.',
      formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  parser.add_argument('--driver', type=str, dest='driver', default='fpga_tio',
                      help='driver of Chameleond')
  parser.add_argument('--log', type=str, dest='log', metavar='PATH',
                      default='/var/log/chameleond',
                      help='write log to this file or - to stderr')
  parser.add_argument('--host', type=str, dest='host', default='0.0.0.0',
                      help='host address of RPC server')
  parser.add_argument('--port', type=int, dest='port', default=9992,
                      help='port number of RPC server')
  parser.add_argument('-v', '--verbose', action='count', dest='verbose',
                      help='increase message verbosity')
  parser.add_argument("driver_args", nargs=argparse.REMAINDER,
                      help='arguments passed to the driver')

  options = parser.parse_args()
  tokens = shlex.split(' '.join(options.driver_args))
  args = [t for t in tokens if '=' not in t]
  kwargs = dict(t.split('=') for t in tokens if '=' in t)

  verbosity_map = {0: logging.INFO, 1: logging.DEBUG}
  verbosity = verbosity_map.get(options.verbose or 0, logging.NOTSET)
  log_format = '%(asctime)s %(levelname)s '
  if options.verbose > 0:
    log_format += '(%(filename)s:%(lineno)d) '
  log_format += '%(message)s'

  log_config = {'level': verbosity,
                'format': log_format}
  if options.log != '-':
    log_config.update({'filename': options.log})
  logging.basicConfig(**log_config)

  try:
    ChameleonServer(options.driver, *args, **kwargs).RunServer(
        options.host, options.port)
  except:  # pylint: disable=W0702
    logging.exception('Failed to start Chameleon server.')
    exit(1)

if __name__ == '__main__':
  main()
